package com.lzy.aspectj;

import com.lzy.annotation.DataScope;
import com.lzy.common.base.BaseEntity;
import com.lzy.context.LocalUser;
import com.lzy.entity.PageDomain;
import com.lzy.entity.SysRoleEntity;
import com.lzy.entity.SysUserEntity;
import com.lzy.security.LoginUser;
import com.lzy.utils.StringUtil;
import com.lzy.utils.StringUtils;
import com.lzy.utils.UserUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * @author lyw
 * @Date 2023/5/16-下午10:13
 */
@Aspect
@Component
public class DataScopeAspect {

  /**
   * 全部数据权限
   */
  public static final String DATA_SCOPE_ALL = "1";

  /**
   * 自定数据权限
   */
  public static final String DATA_SCOPE_CUSTOM = "2";

  /**
   * 部门数据权限
   */
  public static final String DATA_SCOPE_DEPT = "3";

  /**
   * 部门及以下数据权限
   */
  public static final String DATA_SCOPE_DEPT_AND_CHILD = "4";

  /**
   * 仅本人数据权限
   */
  public static final String DATA_SCOPE_SELF = "5";

  /**
   * 数据权限过滤关键字
   */
  public static final String DATA_SCOPE = "dataScope";

  private static Logger log = LoggerFactory.getLogger(DataScopeAspect.class);

  @Before("@annotation(controllerDataScope)")
  public void doBefore(JoinPoint point, DataScope controllerDataScope) throws Throwable
  {
    clearDataScope(point);
    handleDataScope(point, controllerDataScope);
  }

  private void handleDataScope(JoinPoint point, DataScope controllerDataScope) {
    LoginUser loginUser = LocalUser.getLoginUser();
    if (StringUtil.isNotNull(loginUser)) {
      SysUserEntity currentUser = loginUser.getUser();
      // 如果是超级管理员，则不过滤数据
      if (StringUtils.isNotNull(currentUser) && !UserUtil.isAdmin(loginUser.getRoles()))
      {
        dataScopeFilter(point, currentUser, controllerDataScope.deptAlias(),
                controllerDataScope.userAlias());
      }
    }
  }

  /**
   * 数据范围过滤
   *
   * @param joinPoint 切点
   * @param sysUserEntity 用户
   */
  private void dataScopeFilter(JoinPoint joinPoint, SysUserEntity sysUserEntity, String deptAlias, String userAlias) {
    StringBuilder sqlString = new StringBuilder();
    Set<SysRoleEntity> roles = sysUserEntity.getRoles();

    for (SysRoleEntity role : roles) {
      if (role.getDataScope().equals(DATA_SCOPE_ALL)) {
        break;
      } else if (role.getDataScope().equals(DATA_SCOPE_CUSTOM)) {
        sqlString.append(StringUtils.format(
                " OR {}.dept_id IN ( SELECT dept_id FROM sys_role_dept WHERE role_id = {} )",
                deptAlias, role.getRoleId()));
      } else if (role.getDataScope().equals(DATA_SCOPE_DEPT)) {
        sqlString.append(StringUtils.format(" OR {}.dept_id = {}",
                deptAlias,  sysUserEntity.getDeptId()));
      } else if (role.getDataScope().equals(DATA_SCOPE_DEPT_AND_CHILD)) {
        sqlString.append(StringUtils.format(
                " OR {}.dept_id IN ( SELECT dept_id FROM sys_dept WHERE dept_id = {} or find_in_set( {} , ancestors ) )",
                deptAlias, sysUserEntity.getDeptId(), sysUserEntity.getDeptId()));
      } else if (role.getDataScope().equals(DATA_SCOPE_SELF)) {
        if (StringUtils.isNotBlank(userAlias))
        {
          sqlString.append(StringUtils.format(" OR {}.user_id = {} ", userAlias, sysUserEntity.getUserId()));
        }
        else
        {
          // 数据权限为仅本人且没有userAlias别名不查询任何数据
          sqlString.append(StringUtils.format(" OR {}.dept_id = 0 ", deptAlias));
        }
      }
    }

    Object params = joinPoint.getArgs()[0];
    if (StringUtils.isNotNull(params) && params instanceof BaseEntity)
    {
      BaseEntity baseEntity = (BaseEntity) params;
      baseEntity.getParams().put(DATA_SCOPE, " AND (" + sqlString.substring(4) + ")");
    }
  }

  /**
   * 拼接权限sql前先清空params.dataScope参数防止注入
   */
  private void clearDataScope(final JoinPoint joinPoint)
  {
    Object params = joinPoint.getArgs()[0];
    if (StringUtils.isNotNull(params) && params instanceof BaseEntity)
    {
      BaseEntity baseEntity = (BaseEntity) params;
      baseEntity.getParams().put(DATA_SCOPE, "");
    }
  }
}
